<template>
    <div class="div-main">
        <el-form :inline="true" :model="coupon" class="demo-form-inline">
            <el-form-item label="优惠券名称">
              <el-input v-model="coupon.name" placeholder="请输入优惠券名称" style="width: 160px"/>
            </el-form-item>
            <el-form-item label="发放类型">
              <el-select
              v-model="coupon.sendType"
              placeholder="发放类型"
              style="width: 140px"
              >
                <el-option
                  v-for="item in sendTypes"
                  :key="item.id"
                  :label="item.sendName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item label="有效期类型">
              <el-select
              v-model="coupon.validityType"
              placeholder="有效期类型"
              style="width: 120px"
              >
                <el-option
                  v-for="item in validityTypes"
                  :key="item.id"
                  :label="item.validityTypeName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item label="使用门槛类型">
              <el-select
              v-model="coupon.useType"
              placeholder="使用门槛类型"
              style="width: 130px"
              >
                <el-option
                  v-for="item in useTypes"
                  :key="item.id"
                  :label="item.useTypeName"
                  :value="item.id"
              />
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getCouponList()">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="add-div">
            <el-button type="primary" plain @click="add">新增</el-button>
        </div>
        <el-table  :data="couponList" style="width: 100%">
            <el-table-column prop="name" label="优惠券名称" width="180" />
            <el-table-column prop="sendType" label="发放类型" width="80" :formatter="sendTypeFormatter"/>
            <el-table-column prop="count" label="发放张数" width="80" />
            <el-table-column prop="useType" label="使用门槛类型" width="120" :formatter="typeFormatter"/>
            <el-table-column prop="faceValue" label="面值" width="100" />
            <el-table-column prop="exchangeCodeCount" label="已生成兑换个数" width="150" />
            <el-table-column prop="status" label="状态" width="80" :formatter="statusFormatter"/>
            <el-table-column prop="createTime" label="创建时间" width="120" >
              <template v-slot="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="260">
                <template #default="{row}">
                <el-button link type="primary" size="small" @click="edit(row)">修改</el-button>
                <el-button link :disabled="isButtonDisabled(row)" type="primary" size="small" @click="start(row)">发布</el-button>
<!--                <el-button link :disabled="isButtonDisabled(row)" type="primary" size="small" @click="generateCode(row)">生成兑换码</el-button>-->
                  <el-button link type="primary" size="small" @click="generateCode(row)">生成兑换码</el-button>
                <el-button link type="primary" size="small" @click="dele(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

    <div v-show="showPagination">
      <el-pagination :page-size="10" :page-count="totalPage" layout="prev, pager, next" :total="totalCount" @current-change="handlePageChange"/>
    </div>
    <el-dialog width="24%" :modal="coupon" v-model="dialogVisible">
      <el-form ref="formRef" label-width="100px">

        <el-form-item label="优惠券名称">
          <el-input v-model="coupon.name" placeholder="请输入优惠券名称" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="发放张数">
          <el-input v-model="coupon.count" placeholder="请输入发放张数" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="优惠券面值">
          <el-input v-model="coupon.faceValue" placeholder="请输入优惠券面值" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="发放类型">
          <el-select
           v-model="coupon.sendType"
           placeholder="请选择发放类型"
           style="width: 180px"
           @change="handleSendTypeChange"
          >
            <el-option
              v-for="item in sendTypes"
              :key="item.id"
              :label="item.sendName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="所需积分" v-if="isPoint">
          <el-input v-model="coupon.point" placeholder="请输入所需积分" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="有效期类型">
          <el-select
           v-model="coupon.validityType"
           placeholder="请选择有效期类型"
           style="width: 180px"
           @change="handleValidityTypeChange"
          >
            <el-option
              v-for="item in validityTypes"
              :key="item.id"
              :label="item.validityTypeName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期"  v-if="isValidityType1">
          <el-input v-model="coupon.expire" placeholder="请输入有效期" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="有效期单位"  v-if="isValidityType1">
          <el-select
           v-model="coupon.expireUnit"
           placeholder="请选择有效期单位"
           style="width: 180px"
          >
            <el-option
              v-for="item in expireUnits"
              :key="item.id"
              :label="item.expireUnitName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>

        <el-form-item label="有效时间" v-if="isValidityType" style="width: 400px">
          <el-col :span="11">
            <el-date-picker
              v-model="coupon.validityStartTime"
              type="date"
              placeholder="开始时间"
              style="width: 100%"
            />
          </el-col>
        <!-- </el-form-item>
        <el-form-item label="到期时间"  v-if="isValidityType"> -->
          <el-col :span="2" class="text-center">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="coupon.validityEndTime"
              type="date"
              placeholder="到期时间"
              style="width: 100%"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="使用门槛类型">
          <el-select
           v-model="coupon.useType"
           placeholder="请选择使用门槛类型"
           style="width: 180px"
           @change="handleUseTypeChange"
          >
            <el-option
              v-for="item in useTypes"
              :key="item.id"
              :label="item.useTypeName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="满减金额"  v-if="isFullReductionType">
          <el-input v-model="coupon.fullReduce" placeholder="请输入满减金额" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="领取限制">
          <el-select
           v-model="coupon.limit"
           placeholder="请选择领取次数限制"
           style="width: 180px"
           @change="handleLimitChange"
          >
            <el-option
              v-for="item in limits"
              :key="item.id"
              :label="item.limitName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="最大领取次数"  v-if="isLimit">
          <el-input v-model="coupon.limitTimes" placeholder="请输入最大领取次数" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="叠加使用">
          <el-radio-group v-model="coupon.together">
            <el-radio :label="0">可叠加</el-radio>
            <el-radio :label="1">不可叠加</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否专用">
          <el-select
           v-model="coupon.special"
           placeholder="请选择专用类型"
           style="width: 180px"
           @change="handleSpecialChange"
          >
            <el-option
              v-for="item in specialTypes"
              :key="item.id"
              :label="item.specialTypeName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item label="专用类型" v-if="isSpecial">
          <el-select
           v-model="coupon.specialId"
           placeholder="请选择专用类型"
           style="width: 180px"
          >
            <el-option
              v-for="item in specials"
              :key="item.id"
              :label="item.specialName"
              :value="item.id"
          />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button type="primary" @click="hide()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog width="30%" :modal="exchandeCode" v-model="dialogCodeVisible">
      <el-form ref="formRef" label-width="160px">
        <el-form-item label="生成兑换码个数" >
          <el-input v-model="exchandeCode.count" placeholder="每次不得超过50个" style="width: 160px"/>
          <el-form-item>
        </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="generate">生成</el-button>
          <el-button type="primary" @click="generateCancle()">取消</el-button>
        </el-form-item>
     </el-form>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from 'vue'
import { AddCoupon,UpdateCoupon,DeleteCoupon,GenerateCodeCoupon,StartCoupon,ListCoupon} from '@/api/market.js'
import { ElMessage,ElMessageBox } from 'element-plus'

var couponList = ref([]);

var dialogVisible = ref(false);
var dialogCodeVisible = ref(false);
var editOrAdd = ref(false);

var showPagination = ref(false);

var isValidityType=ref(false);
var isValidityType1=ref(false);

var isFullReductionType=ref(false);
var isLimit=ref(false);
var isPoint=ref(false);
var isSpecial=ref(false);


const totalCount = ref(0)
const totalPage = ref(0)

var exchandeCode=ref({
  couponId:"",
  count:""
});

var coupon=ref({
  id:"",
  name:"",//名称
  sendType:"",//发放类型
  validityType:"",//有效期类型：固定和动态
  validityStartTime:"",//有效期开始时间
  validityEndTime:"",//有效期结束时间
  expire:"",//有效期
  expireUnit:"",//有效期单位
  count:"",//张数
  together:"",//是否共用
  useType:"",//使用门槛类型
  faceValue:"",//面值
  fullReduce:"",//满减条件
  limit:"",//是否限领
  limitTimes:"",//限领次数
  createUserId:"",
  point:"",//兑换所需积分
  special:"",//是否专用
  specialId:"",//谁专用
  status:""//状态
});

var expireUnits= ref([{
    id:1,
    expireUnitName:'年'
},{
    id:2,
    expireUnitName:'月'
},{
    id:3,
    expireUnitName:'日'
}])

var specialTypes=ref([
{
    id:0,
    specialTypeName:'否'
},
{
    id:1,
    specialTypeName:'是'
}
]);

var specials= ref([
{
    id:0,
    specialName:'BYD'
},
{
    id:1,
    specialName:'小米'
},{
    id:2,
    specialName:'理想'
},{
    id:3,
    specialName:'蔚来'
},{
    id:4,
    specialName:'小鹏'
},{
    id:5,
    specialName:'问界'
},{
    id:6,
    specialName:'奔驰'
},{
    id:7,
    specialName:'宝马'
},{
    id:8,
    specialName:'奥迪'
}])

var sendTypes= ref([
{
    id:0,
    sendName:'普通发放'
},
{
    id:1,
    sendName:'活动发放'
},{
    id:2,
    sendName:'VIP发放'
},{
    id:3,
    sendName:'活跃用户发放'
},{
    id:4,
    sendName:'积分兑换'
}])

var validityTypes= ref([{
    id:0,
    validityTypeName:'固定有效期'
},{
    id:1,
    validityTypeName:'动态有效期'
}])

var useTypes= ref([{
    id:0,
    useTypeName:'现金'
},{
    id:1,
    useTypeName:'折扣'
},{
  id:2,
  useTypeName:'满减'
}])

var limits= ref([{
    id:0,
    limitName:'不限'
},{
    id:1,
    limitName:'有限'
}])

//初始化数据
getCouponList();

function getCouponList() {
    ListCoupon(coupon.value)
    .then(res => {
      console.info(res.data)
      if (res.data.code == 200000) {
        hide();
        console.info(res.data.data);
        couponList.value=res.data.data.data
        if (res.data.data.totalCount > 0) {
          showPagination = true;
          totalPage.value=res.data.data.totalPage;
          totalCount.value=res.data.data.totalCount;
        }
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
}

function add(){
    dialogVisible.value=true;
    editOrAdd.value=false;
    resetCoupon();
}

function edit(data){
    dialogVisible.value=true;
    editOrAdd.value=true;
    coupon.value={...data};
}

function hide(){
    dialogVisible.value=false;
}

const onSubmit = () => {
    const userInfoJsonString = localStorage.getItem("userInfo");
    const userInfoJson = JSON.parse(userInfoJsonString);
    console.info(userInfoJson);
    coupon.value.createUserId=userInfoJson.id;
    if(editOrAdd.value){
      UpdateCoupon(coupon.value)
      .then(res => {
        if (res.data.code == 200000) {
          hide();
          resetCoupon();
          getCouponList();
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      })
    }else{
      AddCoupon(coupon.value)
      .then(res => {
        console.info(res.data);
        if (res.data.code == 200000) {
          hide();
          resetCoupon();
          getCouponList();
        } else {
          //错误提示框
          ElMessage({
            message: res.data.msg,
            type: 'warning'
          });
        }
      })
    }
}

function generateCode(data){
  dialogCodeVisible.value=true;
  exchandeCode.value.couponId=data.id
}

const generate = () => {
  if(exchandeCode.value.count>150){
    ElMessage({
      type:'warning',
      message:'每次生成兑换码不得超过50个'
    });
    return;
  }
  GenerateCodeCoupon(exchandeCode.value)
    .then(res => {
      if (res.data.code == 200000) {
        dialogCodeVisible.value=false;
        ElMessage({
          type:'success',
          message:'生成成功'
        });
        resetCoupon();
        getCouponList();
      } else {
        //错误提示框
        ElMessage({
          message: res.data.message,
          type: 'warning'
        });
      }
    })
}

function generateCancle(){
  dialogCodeVisible.value=false;
}

//按钮禁用
function isButtonDisabled(row) {
  return row.status != 0;
}

function dele(data){
  ElMessageBox.confirm(
    '是否确认删除',
    '提醒',{
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning'
    }
  ).then(()=>{
    DeleteCoupon(data)
    .then(res => {
      if (res.data.code == 200000) {
        // hide();
        ElMessage({
          type:'success',
          message:'删除成功'
        });
        resetCoupon();
        getCouponList();
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
  }).catch(()=>{
    // ElMessage({
    //   type:'info',
    //   message:'删除取消'
    // })
  })
}
function start(data){
  ElMessageBox.confirm(
    '是否确认发布',
    '提醒',{
      confirmButtonText:'确认',
      cancelButtonText:'取消',
      type:'warning'
    }
  ).then(()=>{
    StartCoupon(data)
    .then(res => {
      if (res.data.code == 200000) {
        // hide();
        ElMessage({
          type:'success',
          message:'开启成功'
        });
        resetCoupon();
        getCouponList();
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
  }).catch(()=>{
    ElMessage({
      type:'info',
      message:'开启取消'
    })
  })
}
function handleSendTypeChange(newVal){
  if(newVal===4){
    isPoint.value=true;
  }else{
    isPoint.value=false;
  }
}

function handleUseTypeChange(newVal){
  if(newVal===2){
    isFullReductionType.value=true;
  }else{
    isFullReductionType.value=false;
  }
}

function handleLimitChange(newVal){
  if(newVal===1){
    isLimit.value=true;
  }else{
    isLimit.value=false;
  }
}

function handleSpecialChange(newVal){
  if(newVal===0){
    isSpecial.value=false;
  }else{
    isSpecial.value=true;
  }
}

function handleValidityTypeChange(newValidityType){
  if(newValidityType===0){
    isValidityType1.value=false;
    isValidityType.value=true;
  }else{
    isValidityType.value=false;
    isValidityType1.value=true;
  }
}

function handlePageChange(newPage){
  coupon.value.pageNum=newPage
  ListCoupon(coupon.value)
    .then(res => {
      if (res.data.code == 200000) {
        hide();
        console.info(res.data.data)
        couponList.value=res.data.data.data
        if (res.data.data.totalCount > 0) {
          showPagination = true;
          totalPage.value=res.data.data.totalPage;
          totalCount.value=res.data.data.totalCount;
        }
      } else {
        //错误提示框
        ElMessage({
          message: res.data.msg,
          type: 'warning'
        });
      }
    })
}

function resetCoupon() {
    Object.keys(coupon.value).forEach(key => {
        coupon.value[key] =  '' ;
    });
    isValidityType1.value=false;
    isValidityType.value=false;
    isFullReductionType.value=false;
    isLimit.value=false;
    isPoint.value=false;
}

function statusFormatter(row, column, cellValue) {
    if (cellValue === 0) {
      return '筹备中';
    } else if (cellValue === 1 || cellValue === 3) {
      return '已发布';
    } else if (cellValue === 2) {
      return '已下线';
    } {
      return '';
    }
}
function typeFormatter(row, column, cellValue) {
    // console.info(cellValue)
    if (cellValue === 0) {
      return '现金';
    } else if (cellValue === 1) {
      return '满减';
    } else if (cellValue === 2) {
      return '折扣';
    }  else {
      return '';
    }
}

function sendTypeFormatter(row, column, cellValue) {
    if (cellValue === 0) {
      return '普通发放';
    } else if (cellValue === 1) {
      return '活动发放';
    } else if (cellValue === 2) {
      return 'VIP发放';
    } else if (cellValue === 3) {
      return '活跃用户发放';
    } else if (cellValue === 4) {
      return '积分兑换';
    } else {
      return '';
    }
}

function formatDate(dateString) {
    // 使用Date对象的parse方法来解析字符串为毫秒时间戳（某些浏览器可能不需要parse，直接用new Date()）
    const date = new Date(dateString);

    // 获取年、月、日，并进行格式化（月份和日需要补零）
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 注意：月份是从0开始的，所以需要+1
    const day = String(date.getDate()).padStart(2, '0');

    // 返回格式化后的日期字符串，你想要的形式是“YYYY-MM-DD”
    return `${year}-${month}-${day}`;
  }
</script>
